package com.geektime.tdd.tdd;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Args {
    public static <T> T parseOption(Class<T> optionsClass, String... args) {
        try {
            List<String> argments = Arrays.asList(args);
            Constructor<?> instance = optionsClass.getDeclaredConstructors()[0];
            //取多个参数
            Object[] objects = Arrays.stream(instance.getParameters()).map(i -> parseOption(i, argments)).toArray();
            return (T) instance.newInstance(objects);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    private static Object parseOption(Parameter parameter, List<String> argments) {
        return parseMap.get(parameter.getType()).parse(argments, parameter.getAnnotation(Option.class));
    }

    //简单定义查表法 直接替换走
    static Map<Class<?>,OptionParse> parseMap = Map.of(
            boolean.class,new BooleanOptionParser()
            ,int.class, new SingleValuedOptionParser(Integer::parseInt),
            String.class, new SingleValuedOptionParser(String::valueOf));


}
